package localizer.main;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity {

	public static String SITE = "http://www.phonefinder.com.br/phone-finder";
	TextView loginText;
	TextView passwordText; 
	TextView mobileNameText; 
	TextView descriptionMobileText;
	ProgressBar progress;
	private Config config;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		TelephonyManager tMgr =(TelephonyManager)getSystemService(TELEPHONY_SERVICE);
		config = Config.getInstance(getApplicationContext());
		
		Button loginButton = (Button) findViewById(R.id.Loginbutton);
		Button creatAccountButton = (Button) findViewById(R.id.creatAccout);
		loginText =(TextView) findViewById(R.id.loginText);
		passwordText =(TextView) findViewById(R.id.passwordText);
		mobileNameText =(TextView) findViewById(R.id.nameMobileText);
		progress = (ProgressBar) findViewById(R.id.progressBar1);
		progress.setVisibility(ProgressBar.GONE);
		descriptionMobileText =(TextView) findViewById(R.id.descriptionMobileText);
		if(config.hasUser(getApplication()) ){ 
			goToMain();
		}
		creatAccountButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(SITE +"/reg_user_mobile/")));

			}
		});
		loginButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				new Thread(){
					@Override
					public void run() {
						handler.sendEmptyMessage(0);
						try {
							Thread.sleep(3000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						postData(mobileNameText.getText().toString(),descriptionMobileText.getText().toString()
								,loginText.getText().toString(),passwordText.getText().toString());

						handler2.sendEmptyMessage(0);
					}

					private Handler handler = new Handler() {
						@Override
						public void handleMessage(Message msg) {
							progress.setVisibility(ProgressBar.VISIBLE);

						}
					};
					private Handler handler2 = new Handler() {
						@Override
						public void handleMessage(Message msg) {
							progress.setVisibility(ProgressBar.GONE);

						}
					};
				}.start();

			}
		});
	}
	private void goToMain() {
		Intent intent2 = new Intent(this,PhoneFinderMain.class);
		startActivity(intent2);
		config = null;
		loginText = null;
		passwordText = null;
		mobileNameText = null;
		descriptionMobileText = null;
		finish();
	}

	private String responseST;
	private Handler  handlerAlert = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Toast.makeText(LoginActivity.this,"Sucess", Toast.LENGTH_LONG).show();
			goToMain();
		}
	};
	private Handler  handlerSetText= new Handler() {
		@Override
		public void handleMessage(Message msg) {
			String mensagem = (String)msg.obj;
			AlertDialog.Builder alert = new AlertDialog.Builder(LoginActivity.this);
			alert.setMessage(mensagem);
			alert.setNeutralButton("Ok", null);
			alert.show();
		}
	};
	public void postData(String name,String description,String login,String password) {
		name = name.replace(' ', '+');
		description = description.replace(' ', '+');
		login = login.replace(' ', '+');
		password = password.replace(' ', '+');
		String url = SITE + "/reg_mobile/?name="+name+"&description="+description+
		"&username="+login+"&password="+password;
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httget = new HttpGet(url);

		try {

			HttpResponse response = httpclient.execute(httget);
			HttpEntity responseEntity = response.getEntity();
			if(responseEntity!=null) {
				responseST = EntityUtils.toString(responseEntity);
			}
			if(checkResponse(responseST)){
				config.createUser(getApplicationContext(), login, responseST);
				config.createTimeLoc(getApplicationContext(),new String(""+(ServiceBroadcastReciever.REPEAT_TIME /1000)) );
				config.createTimeTask(getApplicationContext(),new String(""+(ServiceBroadcastReciever.REPEAT_TIME2 / ( 1000 * 60) ) ));
				config.createTimeRing(getApplicationContext(),new String(""+(RingActivity.TIME_TO_WAIT/1000) ) );
				config.createPassword(getApplicationContext(), password);
				config.setEnableCheckLocByMsg(getApplicationContext(), true);
				config.setEnableCheckRing(getApplicationContext(), true);
				config.setEnableCheckRingByMsg(getApplicationContext(), true);
				config.setEnableCheckUpdateLocation(getApplicationContext(), true);
				config.setEnableUpdateTask(getApplicationContext(), true);
				config.setEnableCheckCheckSim(getApplicationContext(), false);
				config.addEmergencyPhone(getApplicationContext(), "");
				config.addSimId(this, ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getSimSerialNumber());
				handlerAlert.sendEmptyMessage(0);
			}

		} catch (Exception e) {
			Message msg = handlerSetText.obtainMessage();
			msg.obj=e.getMessage();
			handlerSetText.sendMessage(msg);

		}
	}


	private boolean checkResponse(String response){
		String invalidUser = "invalid-username";
		String invalidName ="invalid-name";
		String invalidPassword="invalid-password";
		String invalidDescription="invalid-description";
		Message msg = handlerSetText.obtainMessage();
		boolean resp=false;
		if(response.trim().equals(invalidUser)){
			msg.obj="Invalid User";
			handlerSetText.sendMessage(msg);
		}
		else if(response.trim().equals(invalidName)){
			msg.obj="Invalid Name";
			handlerSetText.sendMessage(msg);
		}
		else if(response.trim().equals(invalidPassword)){
			msg.obj="Invalid Password";
			handlerSetText.sendMessage(msg);
		}
		else if(response.trim().equals(invalidDescription)){
			msg.obj="Invalid Description";
			handlerSetText.sendMessage(msg);
		}
		else{
			resp=true;

		}
		return resp;
	}



}
